package cn.oowoo.rabbitmq.rpc;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import cn.oowoo.rabbitmq.config.RabbitExchangeTypeEnum;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Author ZhangBin
 * @Date 2021/5/8 13:48
 * @Description: 简单消息发送-消费着
 *
 **/
public class RpcConsumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();

        // 声明交换机
        channel.exchangeDeclare(RabbitConfig.EXCHANGE_RPC_NAME, RabbitExchangeTypeEnum.DIRECT.getExchangeType(),false, false, null);

        // 声明队列
        channel.queueDeclare(RabbitConfig.QUEUE_RPC_REQUEST_NAME, false, false, false, null);

        // 绑定队列和交换机
        channel.queueBind(RabbitConfig.QUEUE_RPC_REQUEST_NAME,RabbitConfig.EXCHANGE_RPC_NAME,RabbitConfig.ROUTING_RPC_KEY);

        // 声明回调队列
        channel.queueDeclare(RabbitConfig.QUEUE_RPC_RESPONSE_NAME, false, false, false, null);


        // 创建消费者
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("收到消息msg--->"+msg);
                Map<String,Integer> map = JSON.parseObject(msg,Map.class);
                Integer total =  map.get("a") + map.get("b");
                String resMsg  = map.get("a") +"+" + map.get("b") +"="+total;
                // 把结果发送到回复队列
                channel.basicPublish("",RabbitConfig.QUEUE_RPC_RESPONSE_NAME,null,resMsg.getBytes());
            }
        };

        /**
         * autoAck= false :关闭自动确认，也就是开启手动确认
         * 开始获取消息，注意这里开启了手工应答（关闭自动应答）
         * String basicConsume(String queue, boolean autoAck, Consumer callback)
         *
         */
        channel.basicConsume(RabbitConfig.QUEUE_RPC_REQUEST_NAME, true, consumer);
    }
}
